package com.sq.partner.manager.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.NocarPlan;
import com.sq.partner.manager.mybatis.model.TradProtocolValue;
import com.sq.partner.manager.service.IGatewayNocarInsureService;
import com.sq.partner.manager.service.NoCarProtocolService;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;

@Controller
@RequestMapping("/noCarProtocol")
public class NoCarProtocolController {
	private static Logger logger = LogUtil.getLog(NoCarProtocolController.class);
	
	@Resource
	IGatewayNocarInsureService  nocarInsureService ;
	@Resource
	NoCarProtocolService noCarProtocolService;
	
	
	/**
	 * 跳转协议列表页面
	 */
	@RequestMapping(value = "/list")
	public String insureDefinition(ModelMap model,HttpServletRequest request) throws Exception {
		return "noCarProduct/protocol/list";
	}
	/**
	 * 跳转协议页面加载用户的权限机构
	 */
	@RequestMapping(value = "/queryPrivilegeBranch",method = RequestMethod.POST)
	@ResponseBody
    public Result queryPrivilegeBranch(HttpSession session) throws Exception {
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		logger.info("当前登录用户的userCode为"+user.getUserCode()+",DepartmentStr:"+user.getDepartmentStr());
		
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			return Result.data(noCarProtocolService.queryPrivilegeBranch(user.getDepartmentStr()));
		}
		
		return Result.fail();
		
    }
	/**
	 * 跳转新增页面
	 */
	@RequestMapping(value="/add")
	public String protocolAdd(ModelMap model,HttpServletRequest request) throws Exception{
		//证件类型
		List<DictDto> idType = DictCache.getDict("nocar_id_type");
		//被保人类型
		List<DictDto> bbrType = DictCache.getDict("cjb_bbr_type");
		//洗钱风险
		List<DictDto> moneyRisk = DictCache.getDict("cjb_money_laundering_risk");
		//业务范围
		List<DictDto> businessScope = DictCache.getDict("cjb_business_scope");
		//延保保障范围
		List<DictDto> exScope = DictCache.getDict("ybbzfw");
		model.put("idType", idType);
		model.put("bbrType", bbrType);
		model.put("moneyRisk", moneyRisk);
		model.put("businessScope", businessScope);
		model.put("exScope", exScope);
		return "noCarProduct/protocol/add";
	}
	/**
	 * 加载方案表中带出内容
	 */
	@RequestMapping(value = "/loadGbx")
	public @ResponseBody NocarPlan LoadGbx(HttpSession session,HttpServletRequest request,ModelMap model) throws Exception{
		String planCode=request.getParameter("planCode");
		NocarPlan npl=new NocarPlan();
		npl.setPlanCode(planCode);
		NocarPlan npl2=(NocarPlan)nocarInsureService.queryTradNocarPlanInfo(npl);
		return npl2;
	}
	/**
	 * 执行添加方法
	 */
	@RequestMapping(value="/addProtocolValve")
	public @ResponseBody Result AddProtocolValve(HttpSession session,String planCode,String planName,String businessScope,
			String ex_dept,String startDate,String endDate,String bbr_type,String tbr_name,String tbr_addr,
			String tbr_tel,String bbr_name,String bbr_addr,String bbr_tel,String ex_scope,String ex_warrprid,
			String max_mileage,String vender_warranty_period,String vender_warranty_mileage,String vehicle_use_property,
			String id_type,String id_no,String business_license_no,String market_expense_ratio,String money_laundering_risk,
			String  deptCode,String ex_scope_id,String money_laundering_risk_id) throws Exception{
		
		Map<String,Object> map1=new HashMap<String,Object>();
		//根据出单机构、协议类型、方案类型查询最大流水号
		String deptCode_Sub=deptCode.substring(0, 2);
		map1.put("deptNo", deptCode_Sub);
		map1.put("protocolType", "CJB");
		map1.put("planType", "2");
		String serialNumber=noCarProtocolService.queryMaxSerialNumber(map1);
		
		//生成协议号
		String protocol_no=deptCode.substring(0, 2)+serialNumber+ex_scope_id+ex_warrprid+max_mileage;
		//执行添加
		Map<String,Object> map2=new HashMap<String,Object>();
		map2.put("protocolNo", protocol_no);
		map2.put("protocolType", "CJB");
		map2.put("planCode", planCode);
		map2.put("cond1", bbr_name);
		map2.put("cond2", ex_scope);
		map2.put("cond3", ex_warrprid);
		map2.put("cond4",max_mileage);
		map2.put("cond5", "");
		map2.put("planType", "2");
		
		map2.put("insertTime", new Date());
		map2.put("updateTime", "");
		
		String[] protocolNo=new String[22];
		for(int i=0;i<protocolNo.length;i++){
			protocolNo[i]=protocol_no;
		}
		String[] propKey={"BBR_NAME","EX_SCOPE","EX_WARRPRID","MAX_MILEAGE","BUSI_SCOPE","EX_DEPT","PRTL_START_DATE",
				"PRTL_END_DATE","BBR_TYPE","TBR_NAME","TBR_ADDR","TBR_TEL","BBR_ADDR","BBR_TEL","ID_TYPE","ID_NO","BUSINESS_LICENSE_NO",
				"VENDER_WARRANTY_PERIOD","VENDER_WARRANTY_MILEAGE","VEHICLE_USE_PROPERTY","MARKET_EXPENSE_RATIO","MONEY_LAUNDERING_RISK"};
		String[] propValue={bbr_name,ex_scope,ex_warrprid,max_mileage,businessScope,ex_dept,startDate,endDate,bbr_type,tbr_name,tbr_addr,tbr_tel,
				bbr_addr,bbr_tel,id_type,id_no,business_license_no,vender_warranty_period,vender_warranty_mileage,vehicle_use_property,market_expense_ratio,money_laundering_risk_id};
		String[] descr={"被保人名称","延保保障范围","延长保修期限","保修期限-总里程（质保里程+延保里程）","业务范围","第三方延保服务机构","协议开始日期",
				"协议结束日期","被保人类型","投保人名称","投保人地址","投保人电话","被保人地址","被保险人电话","证件类型",
				"有效身份证号","经营许可证号","厂家质保期限","厂家质保里程数","车辆使用性质","市场费用率","洗钱风险"};
		List<TradProtocolValue> lists=new ArrayList<TradProtocolValue>();
		for(int j=0;j<protocolNo.length;j++){
			TradProtocolValue tradProtocolValue=new TradProtocolValue();
			tradProtocolValue.setProtocolNo(protocolNo[j]);
			tradProtocolValue.setPropKey(propKey[j]);
			tradProtocolValue.setPropValue(propValue[j]);
			tradProtocolValue.setDescr(descr[j]);
			lists.add(tradProtocolValue);
		}
		try{
			noCarProtocolService.addTradProtocolValue(lists, map2);
			return Result.success("添加成功");
		}catch(Exception e){
			return Result.error("添加失败");
		}
	}
	/**
	 * 执行查询方法
	 */
	@RequestMapping(value="/queryTradProtocolValuePage")
	public @ResponseBody Page<Map<String,Object>> QueryTradProtocolValuePage(HttpSession session,Integer size,Integer current,String protocolNo,String planName,String changeDept,String tbrName,String bbrName,String protocol_type,String startDate,String endDate) throws Exception{
		Page<Map<String,Object>> page =new Page<Map<String,Object>>();
		page.setCurrent(current);
		page.setSize(size);
		Map<String, Object> map=SqlUtil.buildPageMap(page);
		//判断查询条件
		if(StrUtil.isNotEmpty(protocolNo)){
			map.put("protocolNo", protocolNo);
		}
		if(StrUtil.isNotEmpty(planName)){
			map.put("planName", planName);
		}
		if(StrUtil.isNotEmpty(changeDept)){
			map.put("deptCode", changeDept);
		}
		if(StrUtil.isNotEmpty(tbrName)){
			map.put("tbrName", tbrName);
		}
		if(StrUtil.isNotEmpty(bbrName)){
			map.put("bbrName", bbrName);
		}
		if(StrUtil.isNotEmpty(protocol_type)){
			map.put("protocolType", protocol_type);
		}
		if(StrUtil.isNotEmpty(startDate)){
			map.put("prtlStartDate", startDate);
		}
		if(StrUtil.isNotEmpty(endDate)){
			map.put("prtlEndDate", endDate);
		}
		map.put("planType", "2");
		
		return noCarProtocolService.queryTradProtocolValuePage(page, map);
		 
	}
	/**
	 * 执行删除方法
	 */
	@RequestMapping(value="/delTradProtocolValue")
	public @ResponseBody Result DelTradProtocolValue(HttpSession session,String protocol_no) throws Exception{
		try{
			noCarProtocolService.delTradProtocolValue(protocol_no);
			return Result.success("删除成功");
		}catch(Exception e){
			return Result.error("该协议对应的产品已生成保单,不能删除协议信息！");
		}
	}
	/**
	 * 执行编辑跳转页面
	 * 
	 */
	@RequestMapping(value="/edit")
	public String edit(ModelMap model,HttpServletRequest request,String protocol_no) throws Exception {
		
		request.setAttribute("protocol_no",URLDecoder.decode(protocol_no, "UTF-8"));
		//证件类型
		List<DictDto> idType = DictCache.getDict("nocar_id_type");
		//被保人类型
		List<DictDto> bbrType = DictCache.getDict("cjb_bbr_type");
		//洗钱风险
		List<DictDto> moneyRisk = DictCache.getDict("cjb_money_laundering_risk");
		//业务范围
		List<DictDto> businessScope = DictCache.getDict("cjb_business_scope");
		//延保保障范围
		List<DictDto> exScope = DictCache.getDict("ybbzfw");
		model.put("idType", idType);
		model.put("bbrType", bbrType);
		model.put("moneyRisk", moneyRisk);
		model.put("businessScope", businessScope);
		model.put("exScope", exScope);
		return "noCarProduct/protocol/add";   
	}
	/**
	 * 
	 * 1.点击编辑时根据protocol_no加载编辑页面
	 * 2.点击协议详情时展示详情
	 * 
	 */
	@RequestMapping(value="/loadByprotocol_no")
	public @ResponseBody String loadByprotocol_no(HttpSession request,String protocol_no) throws Exception{
		
		Map<String,Object> UpdataProtocolmap=noCarProtocolService.queryCJBTradProtocolValueByProtocolNo(protocol_no);
		String jsonStr = JsonUtils.toJson(UpdataProtocolmap);
		return jsonStr;
	}
	/**
	 * 执行修改操作
	 * 
	 */
	@RequestMapping(value="/updateProtocolValve")
	public @ResponseBody Result UpdateProtocolValve(HttpSession session,String planCode,String planName,String businessScope,
			String ex_dept,String startDate,String endDate,String bbr_type,String tbr_name,String tbr_addr,
			String tbr_tel,String bbr_name,String bbr_addr,String bbr_tel,String ex_scope,String ex_warrprid,
			String max_mileage,String vender_warranty_period,String vender_warranty_mileage,String vehicle_use_property,
			String id_type,String id_no,String business_license_no,String market_expense_ratio,String money_laundering_risk,
			String  deptCode,String ex_scope_id,String money_laundering_risk_id,String protocol_no)throws Exception{
		
		
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("protocolNo", protocol_no);
		map.put("protocolType", "CJB");
		map.put("planCode", planCode);
		map.put("cond1", bbr_name);
		map.put("cond2", ex_scope);
		map.put("cond3", ex_warrprid);
		map.put("cond4",max_mileage);
		map.put("cond5", "");
		map.put("planType", "2");
		map.put("insertTime", new Date());
		map.put("updateTime", new Date());
		
		
		String[] protocolNo=new String[22];
		for(int i=0;i<protocolNo.length;i++){
			protocolNo[i]=protocol_no;
		}
		String[] propKey={"BBR_NAME","EX_SCOPE","EX_WARRPRID","MAX_MILEAGE","BUSI_SCOPE","EX_DEPT","PRTL_START_DATE",
				"PRTL_END_DATE","BBR_TYPE","TBR_NAME","TBR_ADDR","TBR_TEL","BBR_ADDR","BBR_TEL","ID_TYPE","ID_NO","BUSINESS_LICENSE_NO",
				"VENDER_WARRANTY_PERIOD","VENDER_WARRANTY_MILEAGE","VEHICLE_USE_PROPERTY","MARKET_EXPENSE_RATIO","MONEY_LAUNDERING_RISK"};
		String[] propValue={bbr_name,ex_scope,ex_warrprid,max_mileage,businessScope,ex_dept,startDate,endDate,bbr_type,tbr_name,tbr_addr,tbr_tel,
				bbr_addr,bbr_tel,id_type,id_no,business_license_no,vender_warranty_period,vender_warranty_mileage,vehicle_use_property,market_expense_ratio,money_laundering_risk_id};
		String[] descr={"被保人名称","延保保障范围","延长保修期限","保修期限-总里程（质保里程+延保里程）","业务范围","第三方延保服务机构","协议开始日期",
				"协议结束日期","被保人类型","投保人名称","投保人地址","投保人电话","被保人地址","被保险人电话","证件类型",
				"有效身份证号","经营许可证号","厂家质保期限","厂家质保里程数","车辆使用性质","市场费用率","洗钱风险"};
		List<TradProtocolValue> lists=new ArrayList<TradProtocolValue>();
		for(int j=0;j<protocolNo.length;j++){
			TradProtocolValue tradProtocolValue=new TradProtocolValue();
			tradProtocolValue.setProtocolNo(protocolNo[j]);
			tradProtocolValue.setPropKey(propKey[j]);
			tradProtocolValue.setPropValue(propValue[j]);
			tradProtocolValue.setDescr(descr[j]);
			lists.add(tradProtocolValue);
		}
		
		try{
			noCarProtocolService.updateTradProtocolValue(lists, map);
			return Result.success("修改成功");
		}catch(Exception e){
			return Result.error("该协议对应的产品已生成保单,不能修改协议信息！");
		}
		
	}
	
	/**
	 *协议详情导出 
	 * @throws Exception
	 */
	@RequestMapping(value = "/exportProtocolMessage",method = RequestMethod.POST)
	public void exportMessage(String protocolNo,String planName,String changeDept,String tbrName,String bbrName,
			String protocolType,String startDate,String endDate,HttpServletResponse response) throws Exception{
		logger.info("开始执行协议详情导出");
		Map<String,Object> map=new HashMap<String,Object>();
		if(StrUtil.isNotEmpty(protocolNo)){
			map.put("protocolNo", protocolNo);
		}
		if(StrUtil.isNotEmpty(planName)){
			map.put("planName", planName);
		}
		if(StrUtil.isNotEmpty(changeDept)){
			map.put("deptCode", changeDept);
		}
		if(StrUtil.isNotEmpty(tbrName)){
			map.put("tbrName", tbrName);
		}
		if(StrUtil.isNotEmpty(bbrName)){
			map.put("bbrName", bbrName);
		}
		if(StrUtil.isNotEmpty(protocolType)){
			map.put("protocolType", protocolType);
		}
		if(StrUtil.isNotEmpty(startDate)){
			map.put("prtlStartDate", startDate);
		}
		if(StrUtil.isNotEmpty(endDate)){
			map.put("prtlEndDate", endDate);
		}
		map.put("planType", "2");
		noCarProtocolService.buildExcel(response,map);
	}
	
}
